//
//  CommentsViewController.m
//  iShop
//
//  Created by svp on 18/12/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CommentsViewController.h"
#import "TextViewCell.h"
#import "iShopAppDelegate.h"
#import "ResourceLoader.h"
#import "Comment.h"
#import "ConstansDefine.h"
#import "Utils.h"
#import "PostCommentRequest.h"

@interface CommentsViewController(Private)

-(void) showFetchError:(NSError*) error;

@end

@implementation CommentsViewController

@synthesize tableView = _tableView;
@synthesize baseProduct = _baseProduct;
@synthesize fetchedResultsController = _fetchedResultsController;
@synthesize leftButton;
@synthesize rightButton;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
		_newPost = NO;
		dictionary = [[NSMutableDictionary alloc] init];
		[dictionary setValue:[Utils getValueForRefKey:kSessionKey] forKey:KSessionKey];
		[dictionary setValue:@"AAAA" forKey:KCommentText];
		NSLog(@"ABF:%@,%@",[dictionary description],_baseProduct);
    }
    return self;
}


/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


-(void) viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	commenters = [[NSArray arrayWithObjects:@"Clover03ti05",@"LibNguyen",@"NguoiXaXu",@"Mê Thời Trang",@"Đẹp",nil] retain];
	commentexts = [[NSArray arrayWithObjects:@"Hàng đẹp.",@"Khi nào có hàng mới vậy?",@"   ",@"....",@"....",nil] retain];
	commentdates = [[NSArray arrayWithObjects:@"16/11/2011",@"15/12/2011",@"25/12/2011",@"5/01/2012",@"13/01/2012",nil] retain];
	[_tableView reloadData];
}

-(void) endEditCell
{
	[_tableView endEditing:YES];
}

-(void) viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
	
}

-(void) viewDidLoad
{
	[super viewDidLoad];
	self.leftButton.title = @"Exit";
	self.navigationItem.leftBarButtonItem = self.leftButton;
	self.rightButton.title = @"New post";
	self.navigationItem.rightBarButtonItem = self.rightButton;
	
	self.navigationItem.rightBarButtonItem.enabled = [Utils getValueForRefKey:kSessionKey] != nil;

	if (![self fetchedResultsController]) {
		NSLog(@"1234567890-=");
	}
	UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endEditCell)];
	
	// For selecting cell.
	gestureRecognizer.cancelsTouchesInView = NO;
	
	[_tableView addGestureRecognizer:gestureRecognizer];
	
	[gestureRecognizer release];
	
}

- (void)dealloc {
	NSLog(@"CommentsViewController dealloc");
	[_tableView release];
    [super dealloc];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	if (_newPost) {
		return 1;
	}
	//return commentexts.count;
	
	return [self.fetchedResultsController sections].count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	
	Comment *comment;
	if ([self.fetchedResultsController sections].count > 0) {
		comment = (Comment*)[self.fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section]];
	}
	
	
	UIView *footView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)] autorelease];
	footView.backgroundColor = [UIColor clearColor];
	//UILabel *totalText = [[[UILabel alloc] initWithFrame:CGRectMake(10, 0, [[NSString stringWithString:_newPost?@"Content": @"clover03ti05"] sizeWithFont:[UIFont systemFontOfSize:20]].width, 60)] autorelease];
	//UILabel *totalText = [[[UILabel alloc] initWithFrame:CGRectMake(10, 0, [[NSString stringWithString:_newPost?@"Content": [commenters objectAtIndex:section]] sizeWithFont:[UIFont systemFontOfSize:20]].width, 30)] autorelease];
	UILabel *totalText = [[[UILabel alloc] initWithFrame:CGRectMake(10, 0, [[NSString stringWithString:_newPost?@"Content": comment.Commenter] sizeWithFont:[UIFont systemFontOfSize:20]].width, 30)] autorelease];

	totalText.backgroundColor = [UIColor clearColor];
	//totalText.text = _newPost?@"Content": [commenters objectAtIndex:section];
	totalText.text = _newPost?@"Content": comment.Commenter;
	UILabel *totalValue = [[[UILabel alloc] initWithFrame:CGRectMake(10 + totalText.frame.size.width, 0, 320 - totalText.frame.size.width - 20, 30)] autorelease];
	totalValue.textAlignment = UITextAlignmentRight;
	totalValue.backgroundColor = [UIColor clearColor];
	totalValue.text = _newPost?@"": [NSString stringWithFormat:@"%@",comment.CommentDate];
	[footView addSubview:totalText];
	[footView addSubview:totalValue];
	return footView;
}

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
	if (_newPost) {
		return 480 - 20 - 60 - 216 - 44;
	}
	//return [[commentexts objectAtIndex:indexPath.section] sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(280, 9999) lineBreakMode:UILineBreakModeWordWrap].height+ 40;

	
	Comment *comment = (Comment*)[self.fetchedResultsController objectAtIndexPath:indexPath];
	NSLog(@"test:%@\n%@",comment.CommentText, NSStringFromCGSize([comment.CommentText sizeWithFont:[UIFont systemFontOfSize:20] forWidth:300 lineBreakMode:UILineBreakModeWordWrap]));
	return [comment.CommentText sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(280, 9999) lineBreakMode:UILineBreakModeWordWrap].height+ 40;
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath 
{
	Comment *comment = (Comment*)[self.fetchedResultsController objectAtIndexPath:indexPath];
	((TextViewCell*)cell).textView.text = comment.CommentText;	
	//((TextViewCell*)cell).textView.text = [commentexts objectAtIndex:indexPath.section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	TextViewCell *cell = (TextViewCell*)[tableView dequeueReusableCellWithIdentifier:@"TextViewCell"];
	if (!cell) {
		NSLog(@"Create cell");
		ResourceLoader *rc = [[[ResourceLoader alloc] initWithNibNamed:@"TextViewCell"] autorelease];
		cell = (TextViewCell*)rc.resource;		
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		cell.textView.scrollEnabled = NO;
		cell.delegate = self;
	}
	if (_newPost) {
		cell.textView.editable = YES;
		cell.textView.scrollEnabled = YES;
		if (_firstDraw) {
			_firstDraw = NO;
			cell.textView.text = [dictionary valueForKey:KCommentText];
		}
		return cell;
	}
	cell.textView.editable = NO;
	cell.textView.scrollEnabled = NO;
	cell.textView.text = @"";
	[self configureCell:cell atIndexPath:indexPath];
	return cell;
}

-(IBAction) savePress:(id) sender;
{
	[_tableView endEditing:YES];
	if (_newPost) {
		PostCommentRequest  *req = [[PostCommentRequest alloc] init];
		[dictionary setValue:_baseProduct.BaseProductID forKey:KBaseProductID];
		[req makeRequest:dictionary];
		_newPost = NO;
		self.leftButton.title = @"Exit";
		self.navigationItem.leftBarButtonItem = self.leftButton;
		self.rightButton.title = @"New post";
		self.navigationItem.rightBarButtonItem = self.leftButton;
		[_tableView reloadData];
	}
	else {
		_newPost = YES;
		_firstDraw = YES;
		[_tableView reloadData];
		self.leftButton.title = @"Cancel";
		self.navigationItem.leftBarButtonItem = self.leftButton;
		self.rightButton.title = @"Post";
		self.navigationItem.rightBarButtonItem = self.leftButton;
	}
}

-(IBAction) cancelPress:(id) sender;
{
	if (_newPost) {
		_newPost = NO;
		self.leftButton.title = @"Exit";
		self.navigationItem.leftBarButtonItem = self.leftButton;
		self.rightButton.title = @"New post";
		self.navigationItem.rightBarButtonItem = self.leftButton;
		[_tableView reloadData];
	}
	else {
		[self.parentViewController dismissModalViewControllerAnimated:YES];
	}
	
}

#pragma mark -
#pragma mark Fetched results controller

- (NSFetchedResultsController *)fetchedResultsController {
	
	if (_fetchedResultsController) {
		return _fetchedResultsController;
	}
	NSManagedObjectContext *moc = [(iShopAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Comment" inManagedObjectContext:moc];
    [fetchRequest setEntity:entity];
    
    [fetchRequest setFetchBatchSize:20];
    
    
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"CommentDate" ascending:NO]]];
	NSPredicate *predicate = [NSPredicate predicateWithFormat:@"BaseProduct == %@",_baseProduct];
	[fetchRequest setPredicate:predicate];
	
	NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:moc sectionNameKeyPath:@"CommentDate" cacheName:nil];
    
	
	self.fetchedResultsController = aFetchedResultsController;
	self.fetchedResultsController.delegate = self;
	
	NSError *error = nil;
	if (![_fetchedResultsController performFetch:&error]) 		
		[self showFetchError:error];
	
    
	return _fetchedResultsController;
}

-(void) showFetchError:(NSError*) error
{
	
	NSLog(@"FetchError:%@",[error description]);
}
#pragma mark -
#pragma mark Fetched results controller delegate


- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView beginUpdates];
}


- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
           atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
	
    switch(type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
            
        case NSFetchedResultsChangeDelete:
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}


- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath {
	
    
    UITableView *tableView = self.tableView;
	
    
    switch(type) {
            
        case NSFetchedResultsChangeInsert:
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
            
        case NSFetchedResultsChangeDelete:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
			break;
            
        case NSFetchedResultsChangeUpdate:
            [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
            break;
            
        case NSFetchedResultsChangeMove:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}


- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
	
    [self.tableView endUpdates];
}

-(void) textViewDidEndEditing:(UITableViewCell*)cell
{
	[dictionary setValue:((TextViewCell*)cell).textView.text forKey:KCommentText];
	NSLog(@"test:%@",[dictionary valueForKey:KCommentText]);
}

@end
